package service

import (
	"errors"
	"github.com/vueadmin/app/admin/internal/dto"
	"github.com/vueadmin/app/admin/internal/model"
	"github.com/vueadmin/app/admin/internal/svc"
	"github.com/vueadmin/app/admin/internal/vo"
	"github.com/vueadmin/utils/conv"
	"gorm.io/gorm"
)

type LoginService struct {
	svcCtx *svc.ServiceContext
}

func NewLoginService(svcCtx *svc.ServiceContext) *LoginService {
	return &LoginService{
		svcCtx: svcCtx,
	}
}

// 后台登录
func (p LoginService) Login(req *dto.LoginReq) (*vo.AdminLogin, error) {
	var entity vo.AdminLogin
	if err := p.svcCtx.Db.Model(&model.Adminuser{}).Preload("Role").Where("user = ?", req.User).Limit(1).First(&entity).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, errors.New("账号不存在！")
		} else {
			return nil, err
		}
	}
	if !conv.EqualsPassword(req.Pwd, entity.Pwd) {
		return nil, errors.New("密码输入错误！")
	}
	if entity.Role.Status == 0 || entity.Status == 0 {
		return nil, errors.New("账户被禁止登录！")
	}
	return &entity, nil
}
